/**
 * Copyright 2024/3/23 the original brandnewdata.com.
 * <p>
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * <p>
 * https://www.apache.org/licenses/LICENSE-2.0
 * <p>
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.zlb.envmodify.transform.config;

import com.zlb.envmodify.util.IOUtil;

import java.io.*;
import java.util.Optional;
import java.util.Properties;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 * @Description
 * @ClassName EnvSettingConfig
 * @Author zhulb
 * @Date 2024/3/23 1:18
 * @Version 0.0.1
 */
public class EnvSettingConfig {

    static Logger logger = Logger.getLogger(EnvSettingConfig.class.getName());

    Properties properties;

    public EnvSettingConfig(String envSettingFileName){
        this.properties = Optional.ofNullable(envSettingFileName).
                map(filePath -> getFileStream(filePath)).
                map(stream -> getPropertiesFromStream(stream)).orElse(null);
    }

    public EnvSettingConfig(File envSettingFile){
        this.properties = Optional.ofNullable(envSettingFile).
                map(file-> getFileStream(envSettingFile)).
                map(stream->getPropertiesFromStream(stream)).orElse(null);
    }

    private Properties getPropertiesFromStream(InputStreamReader propertiesStream) {
        Properties properties = null;
        try (InputStreamReader inputStream = propertiesStream;) {
            properties = new Properties();
            properties.load(inputStream);
        } catch (Exception e) {
            logger.log(Level.WARNING, e, () -> "获取启动环境变量配置异常!");
            System.exit(1);
        } finally {
            IOUtil.closeSilencely(propertiesStream);
        }
        return properties;
    }

    private InputStreamReader getFileStream(File file) {
        try {
            return new InputStreamReader(new BufferedInputStream(new FileInputStream(file)), "UTF-8");
        } catch (Exception e) {
            logger.log(Level.WARNING, e, () -> "获取启动环境变量配置异常!");
            System.exit(1);
        }
        return null;
    }

    private static InputStreamReader getFileStream(String filePath) {
        try {
            return new InputStreamReader(new BufferedInputStream(new FileInputStream(new File(filePath))), "UTF-8");
        } catch (Exception e) {
            logger.log(Level.WARNING, e, () -> "获取启动环境变量配置异常!");
            System.exit(1);
        }
        return null;
    }

    public Properties getProperties(){
        return this.properties;
    }

}
